<?php
    class Auth {
        
        private $ci;
        
        function __construct() {
            $this->ci = &get_instance();            
        }
        
        function login($cond) {
            $user = array();
            $this->ci->db->where($cond);
            $this->ci->db->where('active', 1);
            $res = $this->ci->db->get('users');
            $user = $res->row_array();
            
            if(!empty($user)) {
                $this->ci->session->set_userdata('pos_user_id', $user['id']);
                $userhash = md5($user['id'].$user['username'].$user['email'].config_item('encryption_key'));
                $this->ci->session->set_userdata('pos_user_hash', $userhash);
                return TRUE;
            } else {
                return FALSE;
            }
        }
        
        function login_from_session() {
            if(!$this->ci->session->userdata('pos_user_id')) {
                return FALSE;
            }
            
            $res = $this->ci->db->where('id', $this->ci->session->userdata('pos_user_id'))->where('active', 1)->get('users');
            $user = $res->row_array();
            
            if(!empty($user)) {
                $userhash = md5($user['id'].$user['username'].$user['email'].config_item('encryption_key'));
                if($this->ci->session->userdata('pos_user_hash') !== $userhash) {
                    return FALSE;
                } else {
                    $this->ci->session->set_userdata('pos_user_hash', $userhash);
                    return TRUE;
                }
            } else {
                return FALSE;
            }
        }
        
        function logged_in() {
            if($this->login_from_session()) {
                return TRUE;
            }
            
            return FALSE;
        }
        
        function logout() {
            $this->ci->session->sess_destroy();
        }
    }
?>